import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { isAuthenticated } from "@/utils/auth";
import { ElMessage } from "element-plus";
import store from "@/store";

const routes: Array<RouteRecordRaw> = [
  // 前台布局路由
  {
    path: "/",
    component: () => import("../components/Layout/AppLayout.vue"),
    children: [
      {
        path: "",
        name: "home",
        component: () => import("../views/HomeView.vue"),
        meta: { title: "首页" },
      },
      // 认证相关
      {
        path: "login",
        name: "login",
        component: () => import("../views/auth/LoginView.vue"),
        meta: { title: "登录", requiresGuest: true },
      },
      {
        path: "register",
        name: "register",
        component: () => import("../views/auth/RegisterView.vue"),
        meta: { title: "注册", requiresGuest: true },
      },
      // 帖子相关
      {
        path: "posts",
        name: "posts",
        component: () => import("../views/posts/PostListView.vue"),
        meta: { title: "帖子" },
      },
      {
        path: "posts/create",
        name: "post-create",
        component: () => import("../views/posts/PostCreateView.vue"),
        meta: { title: "发布帖子", requiresAuth: true },
      },
      {
        path: "posts/:id",
        name: "post-detail",
        component: () => import("../views/posts/PostDetailView.vue"),
        meta: { title: "帖子详情" },
      },
      // 悄悄话相关
      {
        path: "whisper",
        name: "whisper",
        component: () => import("../views/whisper/WhisperView.vue"),
        meta: { title: "悄悄话" },
      },
      // 用户相关
      {
        path: "users",
        name: "users",
        component: () => import("../views/users/UserListView.vue"),
        meta: { title: "用户" },
      },
      {
        path: "profile",
        name: "profile",
        component: () => import("../views/users/ProfileView.vue"),
        meta: { title: "个人资料", requiresAuth: true },
      },

      // 调试页面
      {
        path: "debug",
        name: "debug",
        component: () => import("../views/DebugView.vue"),
        meta: { title: "权限调试" },
      },
      // 404页面 - 在前台布局中
      {
        path: ":pathMatch(.*)*",
        name: "not-found",
        component: () => import("../views/NotFoundView.vue"),
        meta: { title: "页面不存在" },
      },
    ],
  },
  // 管理后台独立布局路由
  {
    path: "/admin",
    component: () => import("../views/admin/AdminLayout.vue"),
    meta: { requiresAuth: true, requiresAdmin: true },
    children: [
      {
        path: "",
        name: "admin-dashboard",
        component: () => import("../views/admin/DashboardView.vue"),
        meta: { title: "管理仪表板" },
      },
      {
        path: "reports",
        name: "admin-reports",
        component: () => import("../views/admin/ReportsView.vue"),
        meta: { title: "举报管理" },
      },
      {
        path: "posts",
        name: "admin-posts",
        component: () => import("../views/admin/PostsView.vue"),
        meta: { title: "帖子管理" },
      },
      {
        path: "users",
        name: "admin-users",
        component: () => import("../views/admin/UsersView.vue"),
        meta: { title: "用户管理" },
      },
      {
        path: "categories",
        name: "admin-categories",
        component: () => import("../views/admin/CategoriesView.vue"),
        meta: { title: "分类管理" },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 检查是否有管理员权限
const hasAdminRole = () => {
  const userRoles = store.getters["auth/userRoles"];
  const user = store.getters["auth/user"];
  console.log("检查管理员权限，当前用户:", user);
  console.log("检查管理员权限，当前用户角色:", userRoles);

  if (!userRoles || userRoles.length === 0) {
    return false;
  }

  // 支持多种角色格式检查
  return userRoles.some((role: any) => {
    const roleName = role.name || role.roleName || role;
    console.log("检查角色:", roleName);
    if (typeof roleName === "string") {
      const upperRole = roleName.toUpperCase();
      return (
        upperRole === "ADMIN" ||
        upperRole === "ROLE_ADMIN" ||
        upperRole === "SYSTEM_ADMIN" ||
        upperRole === "ROLE_SYSTEM_ADMIN"
      );
    }
    return false;
  });
};

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - LetHear`;
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth && !isAuthenticated()) {
    ElMessage.warning("请先登录");
    next({ name: "login", query: { redirect: to.fullPath } });
    return;
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin && !hasAdminRole()) {
    ElMessage.error("需要管理员权限");
    next({ name: "home" });
    return;
  }

  // 检查是否需要访客权限（已登录用户不能访问登录页等）
  if (to.meta.requiresGuest && isAuthenticated()) {
    next({ name: "home" });
    return;
  }

  next();
});

export default router;
